import {
  ProductItem,
  addProduct,
  updateProduct,
} from '@/services/product/product';
import type { ProFormInstance } from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { message } from 'antd';
import { useRef } from 'react';

export type ProductModalProps = {
  visible: boolean;
  onVisibleChange: (visible: boolean) => void;
  initialValues?: Partial<ProductItem>;
  onSuccess: () => void;
};

const ProductModal: React.FC<ProductModalProps> = ({
  visible,
  onVisibleChange,
  initialValues,
  onSuccess,
}) => {
  const formRef = useRef<ProFormInstance>();

  return (
    <ModalForm<Omit<ProductItem, 'id' | 'sales'>>
      formRef={formRef}
      title={initialValues ? '编辑商品' : '新增商品'}
      open={visible}
      onOpenChange={onVisibleChange}
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      initialValues={initialValues}
      preserve={false}
      onFinish={async (values) => {
        try {
          let res;
          if (initialValues?.id) {
            res = await updateProduct({ ...values, id: initialValues.id });
          } else {
            res = await addProduct(values);
          }

          if (res.success) {
            message.success(`${initialValues ? '编辑' : '新增'}成功！`);
            onSuccess();
            return true;
          }
          return false;
        } catch (error) {
          message.error(`${initialValues ? '编辑' : '新增'}失败！`);
          return false;
        }
      }}
    >
      <ProFormText
        name="name"
        label="商品名称"
        placeholder="请输入商品名称"
        rules={[{ required: true, message: '请输入商品名称' }]}
      />
      <ProFormText
        name="merchant"
        label="商家"
        placeholder="请输入商家名称"
        rules={[{ required: true, message: '请输入商家名称' }]}
      />
      <ProFormDigit
        name="price"
        label="价格"
        placeholder="请输入商品价格"
        min={0}
        fieldProps={{ precision: 2 }}
        rules={[{ required: true, message: '请输入商品价格' }]}
      />
      <ProFormText
        name="image"
        label="商品图片"
        placeholder="请输入商品图片链接"
        rules={[{ required: true, message: '请输入商品图片链接' }]}
      />
      <ProFormSelect
        name="type"
        label="商品类型"
        placeholder="请选择商品类型"
        options={[
          { label: '食品', value: 'food' },
          { label: '饮料', value: 'drink' },
          { label: '零食', value: 'snack' },
        ]}
        rules={[{ required: true, message: '请选择商品类型' }]}
      />
      <ProFormTextArea
        name="description"
        label="商品简介"
        placeholder="请输入商品简介"
      />
    </ModalForm>
  );
};

export default ProductModal;
